﻿using System;
using System.Windows;
using System.Windows.Forms;
using DuSQL.API;
using System.Data.OleDb;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
namespace DuSQL
{
    /// <summary>
    /// Connect_Add.xaml 的交互逻辑
    /// </summary>
    public partial class Connect_AddSqlServer : Window
    {
        public string ConnectID = "";
        string connstr = "";
        public Connect_AddSqlServer()
        {
            InitializeComponent();
        }
        public Connect_AddSqlServer(string connectID)
        {
            InitializeComponent();
            ConnectID = connectID;
        }
        private void button3_Click(object sender, RoutedEventArgs e)
        {
            this.Hide();
        }

      

        private void btnOK_Click(object sender, RoutedEventArgs e)
        {
            string serverName = txtServerName.Text.Trim();
            if (serverName == "")
                return;
            if (cmbDataBaseName.Text == "")
            {
                System.Windows.MessageBox.Show("请选择数据库!", "温馨提示");
                return;
            }
            if (ConnectID != "")
            {
                DbConnect curConn = Comm.MyConnections.Find(i => i.ConnectID == ConnectID);
                if (curConn != null)
                {
                    //修改链接
                    GetConnectStr(cmbDataBaseName.Text);
                    Comm.MyConnections.Find(i => i.ConnectID == ConnectID).ConnectStr = connstr;
                }
            }
            else
            { 
                DbConnect conn = new DbConnect();
                conn.ConnectID = Guid.NewGuid().ToString();
                conn.ConnectName = serverName+"."+cmbDataBaseName.Text;
                GetConnectStr(cmbDataBaseName.Text);
                conn.ConnectStr = connstr;
                conn.DbType = NodeType.DbConnection_SqlServer;

                if (Comm.MyConnections.Exists(i => i.ConnectStr == conn.ConnectStr))
                {
                    System.Windows.MessageBox.Show("该数据连接已经存在列表中!");                    
                    return;
                }
                Comm.MyConnections.Add(conn);
            }
            Comm.OnChangeData(sender,e);
            this.Hide();
        }

        private void btnTest_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                this.btnTest.IsEnabled = false;
                GetConnectStr("master");
                string sql = "sp_helpdb";

                IList<string> datalist = new List<string>();
                if (connstr.ToLower().Contains("provider=sqloledb"))
                {
                    OleDbConnection conn = new OleDbConnection(connstr);
                    OleDbCommand cmd = new OleDbCommand(sql, conn);
                    if (conn.State == ConnectionState.Closed)
                    {
                        cmd.Connection.Open();
                    }
                    OleDbDataReader drs = cmd.ExecuteReader();
                    //while (dr.Read())
                    //{
                    //    datalist.Add(dr["name"].ToString());
                    //}
                    drs.Dispose();
                    cmd.Connection.Close();

                }
                else
                {
                    SqlConnection conn = new SqlConnection(connstr);
                    SqlCommand cmd = new SqlCommand(sql, conn);
                    if (conn.State == ConnectionState.Closed)
                    {
                        cmd.Connection.Open();
                    }
                    SqlDataReader dr = cmd.ExecuteReader();
                    while (dr.Read())
                    {
                        datalist.Add(dr["name"].ToString());
                    }
                    dr.Dispose();
                    cmd.Connection.Close();
                }




                //获取数据库
                cmbDataBaseName.ItemsSource = datalist;
                btnTest.IsEnabled = true;

            }
            catch (Exception ex)
            {
                System.Windows. MessageBox.Show(ex.Message);
                btnTest.IsEnabled = true;
            }
        }

        private void GetConnectStr(string dataBaseName)//获取连接字符串
        {
            string serverName = txtServerName.Text.Trim();
            string userName = txtUserName.Text.Trim();
            string password = txtPassword.Text;

            string oleDbstr = "Provider=SQLOLEDB;";
            string connstrIsWindows = @"Data Source=" + serverName + ";Integrated Security=SSPI;Initial Catalog=" + dataBaseName + ""; ;
            string connstrNoWindows = @"Data Source=" + serverName + ";Persist Security Info=True;User ID=" + userName + ";Initial Catalog=" + dataBaseName + ";Password=" + password + "";
            connstr = (chkOleDb.IsChecked==true ? oleDbstr : "") + (ChkIsWindowsAuth.IsChecked==true ? connstrIsWindows : connstrNoWindows);
        }

        
    }
}
